<?php
namespace app\controller;

use app\Request;
use app\validate\Player as PlayerValid;

use app\model\Player as PlayerModel;

use app\service\Accredit;
use app\service\Email as EmailService;
/**
 * @author yanxusheng <[<ausheng@foxmail.com>]>
 * @datetime 2023/8/6 14:49
 * @content 玩家管理器
 */
class Player extends Communal
{
    /**
     * @param Request $request
     * @param PlayerValid $valid
     */
    public function Login(Request $request, PlayerValid $valid) {
        if(!$valid->scene('login')->check($request->post())){
            $this->error($valid->getError());
        }

        $username = $request->post('email');
        $password = $request->post('password');

        $resp = PlayerModel::GetInfoByKeyword('email', $username);
        if ($resp->isEmpty()) {
            $this->error('该邮箱并未注册，如有需要请先注册!');
        }
        if ($resp->password != md5($password)) {
            $this->error('密码错误，请核验后再试!');
        }
        if ($resp->status != '1') {
            $this->error('账号状态异常，请联系管理员后再试!');
        }

        // 调用 service
        $service = new Accredit();
        $result = $service->createUsersToken($resp->toArray());
        if (empty($result)) {
            $this->error('登陆失败，请联系管理员!【$service->createUsersToken】');
        }

        $this->success($result);
    }



    /**
     * @param Request $request
     * @param PlayerValid $valid
     */
    public function sendEmail(Request $request, PlayerValid $valid) {
        if(!$valid->scene('send-email')->check($request->post())){
            $this->error($valid->getError());
        }

        $email = $request->post('email');
        $resp_model = PlayerModel::GetInfoByKeyword('email', $email);
        if (!$resp_model->isEmpty()) {
            $this->error('该邮箱已被占用，请更换后再试！');
        }

        $service = new EmailService();
        if (!$service->SendRegisterEmail($email) ) {
            $this->error("发送邮件失败".$service->errorMsg);
        }

        $this->success();
    }





    /**
     * @param Request $request
     * @param PlayerValid $valid
     */
    public function Register(Request $request, PlayerValid $valid) {
        if(!$valid->scene('register')->check($request->post())){
            $this->error($valid->getError());
        }

        $params = $request->post(['email', 'email_code','nickname', 'password']);
        $params['password']     = md5($params['password']);
        $params['player_code']  = guid_code();
        $params['create_time']  = time();

        if (!PlayerModel::SaveInsertInfo($params)) {
            $this->error('注册失败，请联系管理员!【PlayerModel::SaveInsertInfo】');
        }

        $this->success();
    }
}